package org.fuyd.dao;

import java.util.List;

import org.fuyd.exception.MoreCustomerException;
import org.fuyd.model.Customer;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class CustomerDaoImpl implements CustomerDao {

  private HibernateTemplate hibernateTemplate;

  public void add(Customer customer) {
    hibernateTemplate.save(customer);
  }

  public boolean exist(String username) {
    List<?> customers = hibernateTemplate.find("from Customer c where c.username = ?", username);
    if (customers.size() > 0) {
      return true;
    }
    return false;
  }

  public boolean exit(String username, String password) throws MoreCustomerException {
    List<?> list =
        hibernateTemplate.find("from Customer c where c.username = ? and c.password = ?", username,
            password);
    if (list.size() == 1) {
      return true;
    } else if (list.size() > 1) {
      throw new MoreCustomerException("该用户存在多个，请联系管理员");
    } else {
      return false;
    }
  }

  public List<Customer> findAll() {
    @SuppressWarnings("unchecked")
    List<Customer> customers = hibernateTemplate.find("from Customer c");
    return customers;
  }

  public Customer findById(int id) {
    List<?> customers = hibernateTemplate.find("from Customer c where c.id = ?", id);
    return (Customer) customers.get(0);
  }

  public HibernateTemplate getHibernateTemplate() {
    return hibernateTemplate;
  }

  public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
    this.hibernateTemplate = hibernateTemplate;
  }

}
